package edu.tongji.jiaowu.service.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.sf.jasperreports.engine.JasperRunManager;

import com.tongji.quickCRUDQ.dao.jdbc.CommonDao;
import com.tongji.quickCRUDQ.util.StringUtil;

import edu.tongji.jiaowu.service.PrintManager;

public class PrintManagerImpl implements PrintManager {
    private Log log = LogFactory.getLog(getClass());
	private CommonDao commonDao;
	
	  //返回打印数据流
	  /* (non-Javadoc)
	 * @see edu.tongji.jiaowu.service.impl.PrintManager#reportStream(java.lang.String, java.lang.String[])
	 */
	public byte[] reportStream(String jasper,String[] params) throws Exception{
	    Connection conn=getDbConnection();
	    Map parameters=getMap(params);
	    byte[] bytes =JasperRunManager.runReportToPdf(jasper,parameters,conn);
	    conn.close();
	    return bytes;
	  }
	
	  private  Map getMap(String[] params){
		    Map map = new HashMap();
		    try {
		      if(params == null) {
		        return map;
		      }
		      for(int i = 0; i < params.length; i++) {
		        String[] strs = StringUtil.splitStr(params[i], "[$]");
		        if(strs.length==1){
		          map.put(strs[0],"");
		        }
		        else{
		          map.put(strs[0],strs[1]);
		          System.out.println("###"+strs[0]+ "= " + map.get(strs[0]));
		        }
		      }
		    } catch(Exception ex) {
		      ex.printStackTrace();
		      log.error("",ex);
		    }

		    return map;
	  }
	  
	private  Connection getDbConnection() throws SQLException {
		return commonDao.getDataSource().getConnection();
	}


	public CommonDao getCommonDao() {
		return commonDao;
	}

	public void setCommonDao(CommonDao commonDao) {
		this.commonDao = commonDao;
	}
}
